package com.simple.framework.security.custom;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.zuihou.base.R;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler, AuthenticationEntryPoint, InitializingBean {
    private String resultJson = "";
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(401);
        PrintWriter writer = response.getWriter();
        writer.print(resultJson);
        writer.close();
        response.flushBuffer();
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json; charset=utf-8");
        response.setStatus(401);
        PrintWriter writer = response.getWriter();
        writer.print(resultJson);
        writer.close();
        response.flushBuffer();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        R result = R.fail(401, "请登录");
        ObjectMapper objectMapper = new ObjectMapper();
        resultJson = objectMapper.writeValueAsString(result);
    }
}
